import { Module } from "vuex"
import type { IRootState } from "../types"
import type { ILoginState } from "./types"
import type { IAccount } from "@/servers/loginApi/types"
import { loginAccount, getUserInfo, getMenuByRoles, getVerifyCode, loginPhone } from "@/servers/loginApi/loginApi"
import { LStorage } from "@/utils/cacheInfo"
import { TOKEN, USER_INFO, MENU, IS_FOLD } from "@/store/const"
import { menuRouter, menuToPermission, staticRouter, resetRouter } from "@/utils/menu-map"
import { ElNotification } from "element-plus"
import router from "@/router/index"
const loginStore: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: "",
      menus: "",
      permission: new Map<string, string>(),
      verifyCode: ''
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
      if (!LStorage.get(TOKEN)) {
        LStorage.set(TOKEN, token)
      }
    },
    changeUserInfo(state, userInfo: string) {
      state.userInfo = userInfo
      LStorage.remove(USER_INFO)
      LStorage.set(USER_INFO, userInfo)

    },
    changeMenus(state, menus) {
      const staticRouters = staticRouter()
      state.menus = [...staticRouters, ...menus]
      LStorage.remove(MENU)
      LStorage.set(MENU, menus)


      const routers = menuRouter(menus)
      // 菜单封装 动态路由添加
      routers.forEach(item => {

        router.addRoute('main', item)
      })
      // console.log(router.getRoutes());

    },
    changePermission(state, permission) {
      let map = new Map()
      permission.forEach((item: any) => { map.set(item, item) })
      state.permission = map
    },
    changeVerifyCode(state, verifyCode: string) {
      state.verifyCode = verifyCode
    },
    loginOut(state, payload: any[]) {
      resetRouter(payload)
      LStorage.remove(TOKEN)
      LStorage.remove(MENU)
      LStorage.remove(USER_INFO)
      LStorage.remove(IS_FOLD)
      state.token = ""
      state.userInfo = []
      state.menus = []
      state.permission = new Map()
      state.verifyCode = ''
    },

  },
  actions: {
    async utils({ commit, dispatch, state }, result: any) {
      let { code, data: res } = result
      if (code == 1) {
        commit('changeToken', res.token)
        // 2.获当前登录人的信息
        const { code: inFoCode, data } = await getUserInfo()
        if (inFoCode == 1) {
          commit('changeUserInfo', data)
        }
        // 获取登录人的角色信息
        const ids: number[] = []
        data.userRoles.forEach((roleId: { id: any }) => {
          ids.push(roleId.id)
        });
        // 3. 根据角色信息获取菜单
        const { code: menuCode, data: { rows: menus } } = await getMenuByRoles(ids)
        if (menuCode == 1) {
          commit('changeMenus', menus)
        }
        // 4.根据菜单获取按钮权限
        const permission = menuToPermission(menus)

        commit('changePermission', permission)

        if (state.permission.has('system:role:query')) {
          // 获取角色数据
          dispatch('getEntireRoles', null, { root: true })
        }
        if (state.permission.has('system:user:query')) {
          // 获取全部的用户信息
          dispatch('getEntireUsers', null, { root: true })
        }

        if (state.permission.has('system:menu:query')) {
          // 获取全部的菜单信息
          dispatch('getEntireMenus', null, { root: true })
        }

        if (state.permission.has('system:category:query')) {
          // 获取全部的菜单信息
          dispatch('getEntireCategorys', null, { root: true })
        }
        if (state.permission.has('system:article:query')) {
          // 获取全部的菜单信息
          dispatch('getEntireArticles', null, { root: true })
        }
        dispatch('dashboard/TotalAction', null, { root: true })
        // 跳转到首页
        router.replace("/")
      }
    },
    async loginAccountAction({ dispatch }, payload: IAccount) {
      // 1.登录校验
      const data = await loginAccount(payload)
      dispatch('utils', data)
    },
    async getVerifyCodeAction({ commit, dispatch }) {
      const data = await getVerifyCode()
      const { code, data: { verifyCode } } = data
      if (code == 1) {
        commit('changeVerifyCode', verifyCode)
        // 模拟的更加真实一些
        setTimeout(() => {
          ElNotification({
            title: '获取验证码成功',
            message: `验证码:${verifyCode}`,
            type: 'success',
          })
        }, Math.floor(Math.random() * 20) * 1000)

      }
    },
    async loginPhoneAction({ dispatch }, payload: { phone: string, verifyCode: string }) {
      const data = await loginPhone(payload)
      const { code } = data
      if (code == 1) {
        dispatch('utils', data)
      }
    },
    async getUserInfoAction({ commit }) {
      const { code: inFoCode, data } = await getUserInfo()
      if (inFoCode == 1) {
        commit('changeUserInfo', data)
      }
    },
    // 保证vuex 刷新是有数据的
    loadStore({ commit, dispatch, state }) {
      const token = LStorage.get(TOKEN)
      if (token) {
        commit('changeToken', token)
        const userInfo = LStorage.get(USER_INFO)
        if (userInfo) {
          commit('changeUserInfo', userInfo.userInfo)
        }
        const menus = LStorage.get(MENU)
        if (menus) {
          commit('changeMenus', menus.menus)
          commit('changePermission', menuToPermission(menus.menus))
        }
        if (state.permission.has('system:role:query')) {
          // 获取角色数据
          dispatch('getEntireRoles', null, { root: true })
        }
        if (state.permission.has('system:user:query')) {
          // 获取全部的用户信息
          dispatch('getEntireUsers', null, { root: true })
        }

        if (state.permission.has('system:menu:query')) {
          // 获取全部的菜单信息
          dispatch('getEntireMenus', null, { root: true })
        }
        if (state.permission.has('system:category:query')) {

          dispatch('getEntireCategorys', null, { root: true })
        }
        if (state.permission.has('system:article:query')) {

          dispatch('getEntireArticles', null, { root: true })
        }
        if (state.permission.has('system:comment:query')) {
          // 获取全部的菜单信息
          dispatch('comment/commentListAction', null, { root: true })
        }
        dispatch('dashboard/TotalAction', null, { root: true })
      }
    }
  }
}

export default loginStore
